import { User } from "./screens/project-list/search-panel"

const localStorageKey = '__auth_provider_token__'
const baseUrl = 'http://localhost:3001'

export const getToken = () => window.localStorage.getItem(localStorageKey)

export const handleUserResponse = ({user}:{user:User}) => {
  window.localStorage.setItem(localStorageKey, user.token || '')
  return user
}

export const login = (data:{ username:string, password:string}) => {
  return fetch(`${baseUrl}/login`,{
    method:'POST',
    headers:{
      'Content-type':'application/json'
    },
    body:JSON.stringify(data)
  }).then(async response => {
    if(response.ok){
      return handleUserResponse(await response.json())
    }
  })
}

export const register = (data:{ username:string, password:string}) => {
  return fetch(`${baseUrl}/register`,{
    method:'POST',
    headers:{
      'Content-type':'application/json'
    },
    body:JSON.stringify(data)
  }).then(async response => {
    if(response.ok){
      return handleUserResponse(await response.json())
    }
  })
}

export const logout = () => window.localStorage.removeItem(localStorageKey)